import React from "react";
import { Checkbox, Button } from "antd";
import "./index.less";
const ButtonGroup = Button.Group;
interface ICheckboxOption {
  label: string;
  value: any;
}
interface IVCheckboxProps {
  type?: "button" | "normal";
  options: Array<ICheckboxOption>;
  default?: Array<any>;
  [key: string]: any;
}
interface IVCheckboxState {
  selected: { [key: string]: boolean };
}
class VCheckbox extends React.Component<IVCheckboxProps, IVCheckboxState> {
  constructor(props) {
    super(props);
    
    this.state = {
      selected: this.initDefaultState()
    }
  }
  initDefaultState = () => {
    const defaultValue = this.props.default;
    const result = {};
    if (defaultValue) {
      defaultValue.forEach(value => result[value] = true);
    }
    return result;
  }
  onSelectHandle = (value) => {
    const { selected } = this.state;
    selected?.[value] !== undefined
      ? selected[value] = !selected[value]
      : selected[value] = true;
    this.props.onChange && this.props.onChange(Object.keys(selected).filter(key => selected[key]));
    this.setState({ selected: { ...selected } });
  }
  render() {
    const { type, options } = this.props;
    const { selected } = this.state;
    return type === "button" ? <ButtonGroup className="visbar-gui-checkbox-btn">
      {
        options.map(op => <Button key={op.value} type={ selected[op.value] ? "primary" : "default" } size="small" onClick={() => this.onSelectHandle(op.value)}>{ op.label }</Button>)
      }
    </ButtonGroup> : <Checkbox.Group {...this.props} defaultValue={this.props.default}></Checkbox.Group>
  }
}

export default VCheckbox;